package pers.cz.jefconfig.jmx;

import pers.cz.jefconfig.config.JefConfiguration;
import pers.cz.jefconfig.log.LogUtils;
import pers.cz.jefconfig.tools.StringUtils;

import javax.management.NotificationBroadcasterSupport;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @program: JefConfig
 * @description: jmx监听
 * @author: Cheng Zhi
 * @create: 2024-09-16 11:17
 **/
public class JefConfigMonitor extends NotificationBroadcasterSupport implements JefConfigMonitorMBean {
    static JefConfigMonitor monitor;
    private AtomicLong sequence=new AtomicLong();
    private MemoryMXBean m= ManagementFactory.getMemoryMXBean();

    private static String toStr(MemoryUsage m){
        StringBuilder sb=new StringBuilder(64);
        sb.append("-Xms").append(StringUtils.formatSize(m.getInit())).append(' ');
        sb.append("-Xmx").append(StringUtils.formatSize(m.getMax())).append(' ');
        sb.append("Committed:").append(StringUtils.formatSize(m.getCommitted())).append(' ');
        sb.append("Used:").append(StringUtils.formatSize(m.getUsed()));
        return sb.toString();
    }

    public Map<String,String> getSystemProperties(){
        Map<String,String> map=new HashMap<String,String>();
        for(Map.Entry<?,?> e:System.getProperties().entrySet()){
            map.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
        }
        return map;
    }

    @Override
    public void updateSystemProperties(String key, String value) {
        System.setProperty(key, value);
    }

    @Override
    public Map<String,String> getJefConfig() {

        Map<String,String> map=new HashMap<String,String>();
        for(Map.Entry<?,?> e:JefConfiguration.getAllCache().entrySet()){
            map.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
        }
        return map;
    }

    @Override
    public void updateJefConfig(String key, String value) {
        LogUtils.info("to update jefConfig start: key = " + key + " value = " + value);
        key = StringUtils.replaceChars(key, ".-", "_$").toLowerCase();
        JefConfiguration.set(key, value);
    }

    public static JefConfigMonitor getInstance() {
        if(monitor==null)monitor=new JefConfigMonitor();
        return monitor;
    }
}
